package com.gcph.zhuoba.main.common;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

import com.gcph.zhuoba.R;
import com.gcph.zhuoba.util.L;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;


public class BaseActivity extends Activity {
    //设置请求超时10秒钟
    private static final int REQUEST_TIMEOUT = 10000;
    // 设置等待数据超时时间10秒钟
    private static final int SO_TIMEOUT = 10000;
    
    //屏蔽HOME键的标识
    public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
                Toast.makeText(getApplicationContext(), "Crash: " + ex.getMessage(), Toast.LENGTH_LONG).show();
                Log.e("@", "Crash dump", ex);
            }
        });
    }
    /**
     * 全屏
     * @param hideTitle 是否隐藏标题栏
     */
    public void fullScreen(boolean hideTitle)
    {
        getWindow().setFlags
        (
             WindowManager.LayoutParams.FLAG_FULLSCREEN,
             WindowManager.LayoutParams.FLAG_FULLSCREEN
        );
        if(hideTitle)
        {
             requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
    }
    
    
    /**
     * 获得屏幕高度
     * @return
     */
    public int getScreenHeight()
    {
    	 DisplayMetrics dm = new DisplayMetrics();
    	 this.getWindowManager().getDefaultDisplay().getMetrics(dm);

    	 int sH = dm.heightPixels;
    	 return sH;
    }
    
    /**
     * 获得屏幕宽度
     * @return
     */
    public int getScreenWidth()
    {
    	 DisplayMetrics dm = new DisplayMetrics();
    	 this.getWindowManager().getDefaultDisplay().getMetrics(dm);

    	 int sW = dm.widthPixels;
    	 return sW;
    }

    /**
         * 获取网落图片资源
         * @param url
         * @return
         */
       public  Bitmap getHttpBitmap(String url) {
           URL myFileURL;
           Bitmap bitmap = null;
           try {
               myFileURL = new URL(url);
               //获得连接
               HttpURLConnection conn = (HttpURLConnection) myFileURL.openConnection();
               //设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制
               conn.setConnectTimeout(6000);
               //连接设置获得数据流
               conn.setDoInput(true);
               //不使用缓存
               conn.setUseCaches(false);
               //这句可有可无，没有影响
               //conn.connect();
               //得到数据流
               InputStream is = conn.getInputStream();
               //解析得到图片
               bitmap = BitmapFactory.decodeStream(is);
               //关闭数据流
               is.close();
           } catch (Exception e) {
               e.printStackTrace();
           }

           return bitmap;

       }
    /**
     *  获得远程json数据
     * @return
     */
    public String getRemoteJson(String url) {
        String retStr = "[]";
        HttpClient client = this.getHttpClient();
        HttpPost request;
        try {
            request = new HttpPost(new URI(url));
            Log.i("访问地址=", url);
            HttpResponse response = client.execute(request);
            // 判断请求是否成功//200表示请求成功
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    retStr = EntityUtils.toString(entity, "UTF-8");
                    Log.i("得到服务端返回数据", retStr);
                }
            }else
            {
                Toast.makeText(this, "网络连接异常", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "服务器连接异常", Toast.LENGTH_LONG).show();
        }
        return retStr;
    }

    /**
     * 获得httpclient
     * @return
     */
    private HttpClient getHttpClient() {

        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
        HttpClient gcphHttpClient = new DefaultHttpClient(httpParams);

        return gcphHttpClient;
    }
    
    /**
     * 判断是否空字符串
     * @param valiString
     * @return
     */
    public boolean isBlankString(String valiString)
    {
        if(null == valiString || "".equals(valiString) || "null".equals(valiString))
        {
            return true;
        }

        return false;
    }

    /**
     * 时间格式转换
     * @param times
     * @return
     */
    public String getTime(int times){

        StringBuffer sb = new StringBuffer();
        int min1 = times / (60*1000);
        int min2 = times % (60*1000);
        int sec = min2 / 1000;

        if(min1 < 10)
            sb.append("0");
        sb.append(min1).append(":");
        if(sec < 10)
            sb.append("0");
        sb.append(sec);
        return sb.toString();
    }
    /**
	 * 根据球号获得图片
	 * @param no 球编号
	 * @param flag 是否高亮 0不高亮，1高亮
	 * @return
	 */
	public Bitmap getBallBitmapByNo(int no)
    {
		Bitmap bitmap = null;
		switch (no) {

		case 1:
			bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ball1);
			break;
		case 2:
			bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ball2);
			break;
		case 3:
			bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ball3);
			break;
		case 4:
			bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ball4);
			break;
		case 5:
			bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ball5);
			break;
		case 6:
			bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ball6);
			break;
		case 7:
			bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ball7);
			break;
		case 8:
			bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ball8);
			break;
		case 9:
			bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ball9);
			break;
		case 10:
			bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ball10);
			break;
		case 11:
			bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ball11);
			break;
		case 12:
			bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ball12);
			break;
		case 13:
			bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ball13);
			break;
		case 14:
			bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ball14);
			break;
		case 15:
			bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ball15);
			break;
		case 24:
			bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ball16);
			break;
		default:
			break;
		};
		return bitmap;
	}
	
	
	/**
	 * 根据url得文件名
	 * @param url
	 * @return
	 */
	public String getFileNameFromUrl(String url)
	{
		String fileName = null;
		if(null != url)
		{
			int index = url.lastIndexOf("/");
			fileName = url.substring(index);
		}
		return fileName;
	}
	
	/*
	 * 下载视频，并保存到存储卡
	 */
	public void downLoadVedio(final Context context,final VideoView videoView,String remoteFileUrl)
	{
		HttpUtils http = new HttpUtils();
		String url = getResources().getString(R.string.server_root_url) +remoteFileUrl;
		String fileName = getFileNameFromUrl(remoteFileUrl);
		final String  target = Environment.getExternalStorageDirectory().getPath()+"/DCIM/Camera/"+fileName;
		
		File file =new File(target);
		if(file.exists())
		{
			videoView.setVideoURI(Uri.parse(target));
			MediaController mediaco = new MediaController(context);
			videoView.setMediaController(mediaco);
			mediaco.setMediaPlayer(videoView);
			return ;
		}
		
        http.download(url, target, true, true, new RequestCallBack<File>() {  
                    @Override  
                    public void onStart() {  
                    	L.d("=====开始下载=====");
                    }  

                    @Override  
                    public void onLoading(long total, long current, boolean isUploading) {  
                    	int rate = (int) ((double) current/ (double) total *100);
                        L.d("=====下载进度====="+rate);
                    }  

                    @Override  
                    public void onSuccess(ResponseInfo<File> responseInfo) { 
                    	
                    	videoView.setVideoURI(Uri.parse(target));
						MediaController mediaco = new MediaController(context);
						videoView.setMediaController(mediaco);
						mediaco.setMediaPlayer(videoView);
                    }  

                    @Override  
                    public void onFailure(HttpException error, String msg) {  
                    	
                    	 L.d("下载失败====");
                    }
                });  
	}

}
